package com.gitee.cui.basic.create;

import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 第四种创建线程的方式，通过线程池的方式来实现
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/10 9:10
 **/
@Slf4j
public class CreateThread4 {

    private static final int TURN = 5;

    private static final ExecutorService pool = Executors.newFixedThreadPool(3);

    static class RunnableThread implements Runnable {

        @Override
        public void run() {
            for (int i = 1; i < TURN; i++) {
                log.info(ThreadUtil.getCurThreadName() + ", 轮次：{}", i);
                ThreadUtil.sleepMilliSeconds(10);
            }
        }
    }

    static class ReturnedTask implements Callable<Long> {

        @Override
        public Long call() throws Exception {
            long start = System.currentTimeMillis();
            log.info("{} 线程开始运行", ThreadUtil.getCurThreadName());
            Thread.sleep(1000);
            for (int i = 1; i < TURN; i++) {
                log.info(ThreadUtil.getCurThreadName() + ", 轮次：{}", i);
                ThreadUtil.sleepMilliSeconds(10);
            }
            log.info("{} 线程运行结束", ThreadUtil.getCurThreadName());
            return System.currentTimeMillis() - start;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        pool.execute(new RunnableThread());
        pool.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < TURN; i++) {
                    log.info(ThreadUtil.getCurThreadName() + ", 轮次：{}", i);
                    ThreadUtil.sleepMilliSeconds(10);
                }
            }
        });
        Future<Long> future = pool.submit(new ReturnedTask());
        Long time = future.get();
        log.info("异步任务的执行结果：{}", time);
        ThreadUtil.sleepMilliSeconds(Integer.MAX_VALUE);
    }
}
